package com.qumap.edititem;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.qumap.item.ItemInfo;
import com.qumap.item.ItemOnMap;
import com.qumap.common.edit.IDisplay;
import com.qumap.common.event.GlobalEvent;
import com.qumap.common.event.GlobalEventCollection;
import com.qumap.item.IITemInfoDisplay;
import com.qumap.item.event.ItemEventCollection;
import com.qumap.item.event.ItemEvent;
import com.qumap.item.event.ItemEventHandler;
import com.qumap.edititem.update.ItemUpdater;

import javax.inject.Inject;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 10.05.11
 * Time: 18:31
 * To change this template use File | Settings | File Templates.
 */
public class EditItemDisplay implements IDisplay {

	protected IItemEditArea view;
	private EventBus global_event_bus;
    private final ItemUpdater item_updater = new ItemUpdater(this);
    private EditItemListFactory factory;

	private ItemOnMap current_selected_item;

	@Inject
	public EditItemDisplay(EditItemListFactory factory, IItemEditArea view) {
        this.factory = factory;
		this.view = view;
		this.view.setValue(factory.getItemInfoList());
	}

	@Override
	public void setEventBus(EventBus eb) {
		this.global_event_bus = eb;
        factory.setEventBus(eb);
	}

	@Override
	public void init() {
        factory.init();
		initListeners();
		initHandlers();
	}

	private void initListeners() {

        view.getItemList().addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent changeEvent) {
                ItemInfo current_selected_item = view.getSelectedItem();
                view.updateItemFilter(current_selected_item);
            }
        });

		view.getNewButton().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent clickEvent) {
				ItemInfo selected_item_info = view.getSelectedItem();
				ItemOnMap new_item = new ItemOnMap(selected_item_info);
                new_item.setContent(selected_item_info.createContent());
				updateItemInfoContent(new_item);
				ItemEvent new_item_event = ItemEventCollection.getCollection().getEvent(ItemEventCollection.EventType.Created);
				new_item_event.add(new_item);
                current_selected_item = new_item;
                fireEvent(new_item_event);
			}
		});

        view.getSaveButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                if(current_selected_item != null) {
                    if(current_selected_item.isPersisted()) {
                        if(current_selected_item.hasChanges())
                            if(current_selected_item.isFullyLoad())
                                item_updater.update(current_selected_item);
                            else
                                Window.alert("Can t save paritally loaded item");
                    } else {
                        item_updater.save(current_selected_item);
                    }

                }
            }
        });

        view.getDeleteButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                if(current_selected_item != null) {
                    if(!current_selected_item.isPersisted()) {
                        removeItem(current_selected_item);
                        current_selected_item = null;
                    }  else {
                        item_updater.delete(current_selected_item);
                    }
                }
            }
        });

        view.getReloadButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                if(current_selected_item!= null) {
                    current_selected_item.getItemInfo().getFilterDisplay().loadItem(current_selected_item);
                }
            }
        });

        view.getClearAllButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                GlobalEvent clear_all_event = GlobalEventCollection.getCollection().getEvent(GlobalEventCollection.EventType.ClearAll);
                global_event_bus.fireEvent(clear_all_event);
            }
        });

        view.getClearTypedButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                ItemInfo selected_item = view.getSelectedItem();
                ItemOnMap item_type_to_clear = new ItemOnMap(selected_item);
                ItemEvent clear_typed_event = ItemEventCollection.getCollection().getEvent(ItemEventCollection.EventType.ClearTyped);
                clear_typed_event.add(item_type_to_clear);
                global_event_bus.fireEvent(clear_typed_event);
            }
        });

        view.getShowUnsavedItems().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                GlobalEvent show_unsaved = GlobalEventCollection.getCollection().getEvent(GlobalEventCollection.EventType.ShowUnsaved);
                global_event_bus.fireEvent(show_unsaved);
            }
        });

	}

	private void initHandlers() {

		global_event_bus.addHandler(ItemEventCollection.EventType.AddedToMap.getType(), new ItemEventHandler() {
			@Override
			public void onItemEvent(ItemEvent event) {
                current_selected_item = event.getFirstItem();
                IITemInfoDisplay display = current_selected_item.getItemInfo().getItemDisplay();
				display.getStateFromItem(event.getFirstItem());
			}
		});

		global_event_bus.addHandler(ItemEventCollection.EventType.Select.getType(), new ItemEventHandler() {
			@Override
			public void onItemEvent(ItemEvent event) {
                ItemOnMap event_item = event.getFirstItem();
                if(!event_item.isFullyLoad() && view.needReloadOnSelect()) {
                    event_item.getItemInfo().getFilterDisplay().loadItem(event_item);
                } else {
    				current_selected_item = event_item;
	    			updateItemInfoContent(current_selected_item);
                }
			}
		});
	}

    public void removeItem(ItemOnMap item_to_remove) {
        item_to_remove.getItemInfo().getItemDisplay().clear();
        ItemEvent item_delete_event = ItemEventCollection.getCollection().getEvent(ItemEventCollection.EventType.Delete);
        item_delete_event.add(item_to_remove);
        fireEvent(item_delete_event);

    }

	private void updateItemInfoContent(ItemOnMap new_item) {
		saveStateToItem();
		new_item.getItemInfo().getItemDisplay().getStateFromItem(new_item);
		view.updateItemInfo(new_item.getItemInfo());
	}

	private void saveStateToItem() {
		if(current_selected_item != null) {
			current_selected_item.getItemInfo().getItemDisplay().putStateToItem(current_selected_item);
		}
	}

    public void fireEvent(ItemEvent global_event) {
        global_event_bus.fireEvent(global_event);
    }

	@Override
	public void onStop() {

	}

	@Override
	public Widget asWidget() {
		return view.asWidget();
	}
}
